package com.servlet.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Title: MyFilter01
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2023/12/26 9:14
 */
public class MyFilter01 implements Filter {
    /**
     * 初始配置文件  init初始化加载
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String user = filterConfig.getInitParameter("user");
        System.out.println("过滤器已被创建....."+user);

    }

    /**
     * 过滤
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        // 判断请求头是否存在token  如果存在 放行 不存在不放行
        String token = request.getHeader("token");
        if(token == null || "".equals(token)) {
            response.setHeader("Content-Type","text/plain;charset=utf-8");
            response.getWriter().write("用户尚未登录!");
            return;
        }

        // 在进入到下一个servlet之前执行
        System.out.println("A 过滤器执行了.....");
        // 放行
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
